﻿using System;

using System.Text;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// 
    /// 错误对象类
    /// ECMA 15.11
    /// </summary>
    public class NativeError : IdScriptableObject
    {

        private const int
            Id_constructor = 1,
            Id_toString = 2,
            Id_toSource = 3,

            MAX_PROTOTYPE_ID = 3;

        private static Object ERROR_TAG = "Error";

      public  static void init(Scriptable scope, bool sealed1)
        {
            NativeError obj = new NativeError();
            ScriptableObject.putProperty(obj, "name", "Error");
            ScriptableObject.putProperty(obj, "message", "");
            ScriptableObject.putProperty(obj, "fileName", "");
            ScriptableObject.putProperty(obj, "lineNumber", 0);
            obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed1);
        }

      public  static NativeError make(Context cx, Scriptable scope,
                                IdFunctionObject ctorObj, Object[] args)
        {
            Scriptable proto = (Scriptable)(ctorObj.get("prototype", ctorObj));

            NativeError obj = new NativeError();
            obj.setPrototype(proto);
            obj.setParentScope(scope);

            int arglen = args.Length;
            if (arglen >= 1)
            {
                ScriptableObject.putProperty(obj, "message",
                        ScriptRuntime.toString(args[0]));
                if (arglen >= 2)
                {
                    ScriptableObject.putProperty(obj, "fileName", args[1]);
                    if (arglen >= 3)
                    {
                        int line = ScriptRuntime.toInt32(args[2]);
                        ScriptableObject.putProperty(obj, "lineNumber",
                                line);
                    }
                }
            }
            if (arglen < 3 && cx.hasFeature(Context.FEATURE_LOCATION_INFORMATION_IN_ERROR))
            {
                // Fill in fileName and lineNumber automatically when not specified
                // explicitly, see Bugzilla issue #342807
                int[] linep = new int[1];
                String fileName = Context.getSourcePositionFromStack(linep);
                ScriptableObject.putProperty(obj, "lineNumber",
                        linep[0]);
                if (arglen < 2)
                {
                    ScriptableObject.putProperty(obj, "fileName", fileName);
                }
            }
            return obj;
        }


        public override String getClassName()
        {
            return "Error";
        }


        public override String ToString()
        {
            return js_toString(this);
        }


        public override void initPrototypeId(int id)
        {
            String s;
            int arity;
            switch (id)
            {
                case Id_constructor: arity = 1; s = "constructor"; break;
                case Id_toString: arity = 0; s = "toString"; break;
                case Id_toSource: arity = 0; s = "toSource"; break;
                default: throw new ArgumentException(id.ToString());
            }
            initPrototypeMethod(ERROR_TAG, id, s, arity);
        }


        public override Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                                 Scriptable thisObj, Object[] args)
        {
            if (!f.hasTag(ERROR_TAG))
            {
                return base.execIdCall(f, cx, scope, thisObj, args);
            }
            int id = f.methodId();
            switch (id)
            {
                case Id_constructor:
                    return make(cx, scope, f, args);

                case Id_toString:
                    return js_toString(thisObj);

                case Id_toSource:
                    return js_toSource(cx, scope, thisObj);
            }
            throw new ArgumentException(id.ToString());
        }

        private static String js_toString(Scriptable thisObj)
        {
            return getString(thisObj, "name") + ": " + getString(thisObj, "message");
        }

        private static String js_toSource(Context cx, Scriptable scope,
                                          Scriptable thisObj)
        {
            // Emulation of SpiderMonkey behavior
            Object name = ScriptableObject.getProperty(thisObj, "name");
            Object message = ScriptableObject.getProperty(thisObj, "message");
            Object fileName = ScriptableObject.getProperty(thisObj, "fileName");
            Object lineNumber = ScriptableObject.getProperty(thisObj, "lineNumber");

            StringBuilder sb = new StringBuilder();
            sb.Append("(new ");
            if (name == NOT_FOUND)
            {
                name = Undefined.instance;
            }
            sb.Append(ScriptRuntime.toString(name));
            sb.Append("(");
            if (message != NOT_FOUND
                || fileName != NOT_FOUND
                || lineNumber != NOT_FOUND)
            {
                if (message == NOT_FOUND)
                {
                    message = "";
                }
                sb.Append(ScriptRuntime.uneval(cx, scope, message));
                if (fileName != NOT_FOUND || lineNumber != NOT_FOUND)
                {
                    sb.Append(", ");
                    if (fileName == NOT_FOUND)
                    {
                        fileName = "";
                    }
                    sb.Append(ScriptRuntime.uneval(cx, scope, fileName));
                    if (lineNumber != NOT_FOUND)
                    {
                        int line = ScriptRuntime.toInt32(lineNumber);
                        if (line != 0)
                        {
                            sb.Append(", ");
                            sb.Append(ScriptRuntime.toString(line));
                        }
                    }
                }
            }
            sb.Append("))");
            return sb.ToString();
        }

        private static String getString(Scriptable obj, String id)
        {
            Object value = ScriptableObject.getProperty(obj, id);
            if (value == NOT_FOUND) return "";
            return ScriptRuntime.toString(value);
        }


        public override int findPrototypeId(String s)
        {
            int id;
            // #string_id_map#
            // #generated# Last update: 2007-05-09 08:15:45 EDT
            id = 0; String X = null; int c;
            int s_length = s.Length;
            if (s_length == 8)
            {
                c = s.ToCharArray()[3];
                if (c == 'o') { X = "toSource"; id = Id_toSource; }
                else if (c == 't') { X = "toString"; id = Id_toString; }
            }
            else if (s_length == 11) { X = "constructor"; id = Id_constructor; }
            if (X != null && X != s && !(X == s)) id = 0;
            goto L0;

        L0: ;
            // #/generated#
            return id;
        }

    }
}
